//
//  LGTRWZPayVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/27.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
enum PayType:Int{
    case PostPayType = 0  //发布费用
    case ApendPayType = 1 //追加订单
}

class LGTRWZPayVC: LGTBaseVC {

    var fromNav:UINavigationController?//来自哪个控制器
    var payMonyLabel:UILabel?
    var currentMonyLabel:UILabel?
    var noMoneyLabel:UILabel?
    var buttonArray:Array<UIButton> = []
    //发步 submitDataInfo  ====》  到  LGTRWZSubmitOrderModel看参数说明
    var submitDataInfo:Dictionary<String, Any?>?
    var payType:PayType = PayType.PostPayType //是不是发布的
    var currentSelectType:Int = 10   // 0余额, 1微信, 2支付宝  1-微信,2-支付宝,10-余额
    var amount:Int = 0 //零钱
    override func viewDidLoad() {
        super.viewDidLoad()
        //微信支付
        NotificationCenter.default.addObserver(self, selector: #selector(wxPaySuccessAction), name: WXPay_ReCharge_Note, object: nil)
    }

    @objc func wxPaySuccessAction(note:Notification){
        //支付完成回掉
        self.dismiss(animated: false, completion: nil)
        if self.fromNav != nil{
            self.fromNav?.popToRootViewController(animated: false)
            NotificationCenter.default.post(name: Pay_Success_Note, object: nil)
            let vc:LGTRWZPaySuccessVC = LGTRWZPaySuccessVC()
            self.fromNav!.pushViewController(vc, animated: true)
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: WXPay_ReCharge_Note, object: nil)
    }
    
    override func setUI() {
        super.setUI()
        self.view.backgroundColor = BlackAlphaColor
        let backView:UIView = UIView.init()
        backView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(backClick))
        backView.addGestureRecognizer(tap)
        let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(backClick))
        self.view.addGestureRecognizer(tap2)
        
        backView.backgroundColor = UIColor.white
        self.view.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(SizeFit(367) + IPHONETabbar_DIS())
        }
        
        let titleLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.center, textColor: TextColor, fontSize: SizeFitFloat(18), text: "你需支付")
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFitFloat(18))
            make.top.equalTo(SizeFitFloat(19))
        }
        
        
        let payMoney:Double = self.submitDataInfo?["payMoney"] as? Double ?? 0
        let payMoneyStr:String = String.init(format: "¥%.2f", payMoney)
        self.payMonyLabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.center, textColor: ColorUtil(color: 0xF2421F), fontSize: SizeFitFloat(30), text: payMoneyStr)
        backView.addSubview(self.payMonyLabel!)
        self.payMonyLabel!.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFitFloat(30))
            make.top.equalTo(SizeFitFloat(50))
        }
        
        let amountStr:String = String.init(format: "¥%.2f", Double(self.amount) / 100.0)
        self.currentMonyLabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.center, textColor: GrayColor, fontSize: SizeFitFloat(15), text: amountStr)
        backView.addSubview(self.currentMonyLabel!)
        self.currentMonyLabel!.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFitFloat(15))
            make.top.equalTo(SizeFitFloat(91))
        }
        
        let line:UIView = LGTViewCreateUtil.share.createLineView()
        backView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.left.equalTo(SizeFitFloat(13))
            make.right.equalTo(-SizeFitFloat(11))
        }
        
        let payWayLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "请选择付款方式")
        backView.addSubview(payWayLabel)
        payWayLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFitFloat(13))
            make.height.equalTo(SizeFitFloat(18))
            make.top.equalTo(SizeFitFloat(141))
        }
        
        let array:Array<Dictionary<String, Any>> = [["title":"余额支付", "icon":"balancepayment", "type":10],
                                                    ["title":"微信支付", "icon":"wechatpayment", "type":1],
                                                    ]
//                                                    ["title":"支付宝支付", "icon":"alipaypayment", "type":2]]
//
        for i in 0..<array.count{
            let d:Dictionary<String, Any> = array[i]
            let image:String = d["icon"] as! String
            let title:String = d["title"] as! String
            let imageView:UIImageView = LGTViewCreateUtil.share.createImageView(image: image)
            backView.addSubview(imageView)
            imageView.snp.makeConstraints { (make) in
                make.left.equalTo(SizeFit(SizeFit(25)))
                make.height.width.equalTo(SizeFit(20))
                make.top.equalTo(SizeFit(Double(181 + i * 43)))
            }
            
            let payTitleLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: title)
            backView.addSubview(payTitleLabel)
            payTitleLabel.snp.makeConstraints { (make) in
                make.left.equalTo(SizeFit(53))
                make.height.equalTo(18)
                make.centerY.equalTo(imageView)
            }
            
            if i == 0{
                self.noMoneyLabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: GrayColor, fontSize: SizeFitFloat(12), text: "当前余额不足")
                backView.addSubview(self.noMoneyLabel!)
                self.noMoneyLabel!.snp.makeConstraints { (make) in
                    make.centerY.equalTo(imageView)
                    make.height.equalTo(SizeFit(12))
                    make.left.equalTo(payTitleLabel.snp_rightMargin).offset(SizeFit(10))
                }
            }
            
            let button:UIButton = LGTViewCreateUtil.share.createLGTButton(image: "unchecked", selected: "selection", dW: SizeFitFloat(5), dH: SizeFitFloat(5))
            backView.addSubview(button)
            button.snp.makeConstraints { (make) in
                make.right.equalTo(-SizeFit(22))
                make.width.height.equalTo(SizeFit(20))
                make.centerY.equalTo(imageView)
            }
            
            let type:Int = d["type"] as? Int ?? 0
            button.tag = type
            button.addTarget(self, action: #selector(choseAction), for: UIControl.Event.touchUpInside)
            self.buttonArray.append(button)
        }
        
        let sureButton:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "确认支付", font: Font_Normal_18, color: UIColor.white, selectedColor: UIColor.white, corner: SizeFitFloat(22), backColor: YellowColor)
        backView.addSubview(sureButton)
        sureButton.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFitFloat(25))
            make.right.equalTo(SizeFitFloat(-21))
            make.height.equalTo(SizeFitFloat(44))
            make.top.equalTo(SizeFitFloat(306))
        }
        sureButton.addTarget(self, action: #selector(sureAction), for: UIControl.Event.touchUpInside)
        
        //默认 零钱
        if payMoney > (Double(self.amount) / 100.0){
            self.noMoneyLabel?.isHidden = false
            self.buttonArray[0].isUserInteractionEnabled = false
            self.choseAction(sender: self.buttonArray[1])
        }else{
            self.noMoneyLabel?.isHidden = true
            self.choseAction(sender: self.buttonArray[0])
        }
    }
    
    @objc func choseAction(sender:UIButton){
        let index:Int = sender.tag
        self.currentSelectType = index
        for btn in self.buttonArray{
            if btn.tag == index{
                btn.isSelected = true
            }else{
                btn.isSelected = false
            }
        }
    }

//    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        self.dismiss(animated: false, completion: nil)
//    }
    
    @objc func sureAction(){

        //发布
        if self.payType == PayType.PostPayType{
            self.postPay()
        }
        //追加订单
        else if self.payType == PayType.ApendPayType{
            self.appendPay()
        }
    }
    
    func appendPay(){
        let param:Dictionary<String, Any> = ["pay_type":self.currentSelectType,
                                             "id":self.submitDataInfo?["id"] as? Int ?? 0,
                                             "top_time_limit": self.submitDataInfo?["top_time_limit"] as? Int ?? 0,
                                             "end_time":self.submitDataInfo?["end_time"] as? String ?? "",
                                             "num":self.submitDataInfo?["num"] as? Int ?? 0]
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Add_URL, param: param, showMessage: true, success: { (json) in
            weakSelf?.payAction(json: json)
        }) { (json) in
            
        }
    }
    
    func postPay(){
        let type:PostNameModel = self.submitDataInfo?["type"] as! PostNameModel
        let os:PostNameModel = self.submitDataInfo?["os"] as! PostNameModel
        let projectName:String = self.submitDataInfo?["projectName"] as! String
        let taskRequest:String = self.submitDataInfo?["taskRequest"] as! String
        let workTime:PostNameModel = self.submitDataInfo?["workTime"] as! PostNameModel
        let reviewTime:PostNameModel = self.submitDataInfo?["reviewTime"] as! PostNameModel
        let workTimes:PostNameModel = self.submitDataInfo?["workTimes"] as! PostNameModel
        let workPriceStr:String = self.submitDataInfo?["workPrice"] as! String
        let taskCount:String = self.submitDataInfo?["taskCount"] as! String
        let toptime:String = self.submitDataInfo?["toptime"] as? String ?? ""
        let offline:String = self.submitDataInfo?["offline"] as? String ?? ""
        // 支付方式[1-微信,2-支付宝,10-余额]
        let payType:Int = self.currentSelectType
        let workPirce:Int = Int((Float(workPriceStr) ?? 0) * Float(100))
        
        //步骤
        let stepArray:Array<Dictionary<String, Any>> = self.submitDataInfo?["step"] as? Array<Dictionary<String, Any>> ?? []
        //数据转换
        //var stepDataArray:Array<Dictionary<String, Any>> = []
        var stepDataArray:Array<String> = []
        for i in 0..<stepArray.count{
            // dict 对应 LGTRWZSubmitOrderModel 的 LGTRWZStepOrderModel
            let dict:Dictionary<String, Any> = stepArray[i]
            var stepSubmitInfo:Dictionary<String, Any> = [:]
            stepSubmitInfo["type"] = self.getType(info: dict)
            let title:String = dict["stepText"] as? String ?? ""
            stepSubmitInfo["title"] = title
            
            let message:String = dict["subText"] as? String ?? ""
            stepSubmitInfo["message"] = message
            
            var selectInfo:Dictionary<String, Any>? = dict["selectInfo"] as? Dictionary<String, Any>
            if selectInfo != nil{
                let imageID:Int = selectInfo?["id"] as? Int ?? 0
                stepSubmitInfo["image"] = imageID
            }
            
            stepDataArray.append(BaseUtil.baseUtil.dicValueString(stepSubmitInfo) ?? "")
        }
        
        let stepStr = "[\(stepDataArray.joined(separator: ","))]"
        let param:Dictionary<String, Any> = ["type": type.value!, // 任务类型
            "task_os": os.value!, // 支持操作系统
            "title": projectName, // 标题
            "content":taskRequest, // 内容
            "complete_time_limit": workTime.value!, //完成时限(秒)
            "review_time_limit":reviewTime.value!, //审核时限(秒)
            "end_time": offline, // 下线日期
            "total_count": taskCount, //总量
            "pay_type":payType, //支付类型
            "frequency":workTimes.value!, // 次数[1-每人一次,2-每人三次,3-每日一次]
            "price":workPirce, //单价(分)
            "top_time_limit":toptime,
            "step": stepStr
        ]
        
        //发布成功
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Post_URL, param: param, showMessage: true, success: { (json) in
            weakSelf?.payAction(json: json)
        }) { (json) in
            
        }
    }
    
    //支付
    func payAction(json:Dictionary<String, Any>){
        //选择余额支付
        if self.currentSelectType == 10{
            self.dismiss(animated: false, completion: nil)
            NotificationCenter.default.post(name: Pay_Success_Note, object: nil)
            //关闭当前页面 清理数据
            NotificationCenter.default.post(name: WXPay_ReCharge_Note, object: nil)
        }else{
            //微信支付
            let data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            LGTViewUtil.share.wxPay(data: data)
        }
    }
    
    func getType(info:Dictionary<String, Any>) -> Int{
        let isurl:Bool = info["isurl"] as? Bool ?? false
        //        1、输入网址（最多可创建1条）；
        if isurl == true{
            return 1
        }
        
        //        3、复制数据（最多可创建8条）；
        let copy:Bool =  info["copy"] as? Bool ?? false
        if copy == true{
            return 3
        }
        
        //        6、收集信息（最多可创建1条）；
        let collection:Bool =  info["collection"] as? Bool ?? false
        if collection == true{
            return 6
        }
        
        //var index:Int?  //0上传验证图  1上传说明图 2上传二维码
        //   2、上传二维码（最多可创建8条） 4、图文说明（最多可创建8条） 5、验证图（最多可创建8条）
        
        return info["type"] as? Int ?? 0
        
//        let index:Int = info["index"] as? Int ?? 0
//        let dataInfo = ["0": 5,
//                        "1": 4,
//                        "2": 2]
//        let key:String = String(index)
//        return dataInfo[key] ?? 5
    }
    
    @objc func backClick(tap:UITapGestureRecognizer){
        if tap.view == self.view{
            self.dismiss(animated: false, completion: nil)
        }
    }
}
